#!/usr/bin/python
# coding=utf-8
import random, sys, logging, time, traceback
from xpy3lib.utils import db_utils as util
from xpy3lib.utils.XUtils import XUtils

from datetime import datetime
from datetime import date
from flask import Flask, request, json, jsonify, abort, make_response
# from apscheduler.schedulers.background import BackgroundScheduler
# from apscheduler.executors.pool import ProcessPoolExecutor
from model.config import app_config
from model.MODELJob import MODELJob

#
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

#
profile = (sys.argv[1].split("=", 1)[-1]) if len(sys.argv) > 1 else 'dev'
config = app_config[profile]


@app.route('/api-model/get_info.sdo', methods=["GET", "POST"])
def test_index_1():
    response_dict = {'message': 'success---hi--prm-server'}
    return json.dumps(response_dict)


@app.route('/api-model/', methods=["GET", "POST"])
def test_index_0():
    response_dict = {'message': 'success---hi--model-server'}
    return json.dumps(response_dict)


@app.route('/api-model/request_model.sdo', methods=["GET", "POST"])
def request_model():
    table_1 = dict()
    table_2 = dict()
    response_dict = dict()

    body_dict = None
    if request.method == 'POST':
        try:
            try:
                request_json_text = request.get_data()
                body_dict = json.loads(request_json_text.decode('utf-8'))
            except Exception as e:
                body_dict = request.form.to_dict()
                # NOTE below is the pseudo code of post data fetching
                # postdata = request.form['id']
                # file = request.files['file']
        except Exception as e:
            body_dict = None
            traceback.print_exc()
    else:
        body_dict = request.args.to_dict(flat=True)

    #
    if body_dict is not None:
        try:
            #
            # body_dict['type'] = int(body_dict['type'])
            # NOTE
            for k, v in body_dict.items():
                body_dict[k] = float(body_dict[k])
            success = True
        except Exception as e:
            success = False
            msg = f'invalid_parameter_type--{str(e)}'
            data = None
            timestamp = None

        if success:
            try:
                success, msg, data, timestamp, table_1, table_2 \
                    = run_model_job(p_config=config, p_ver=body_dict['ver'], p_type=body_dict['type'])
            except Exception as e:
                success = False
                msg = f'run_model_job_failed---with--{str(body_dict)}--{str(e)}'
                data = None
                timestamp = None
    else:
        success = False
        msg = 'invalid_http_request_parameters'
        data = None
        timestamp = None
    response_dict['success'] = success
    response_dict['message'] = msg
    response_dict['timestamp'] = timestamp
    # response_dict['data'] = data
    response_dict['table_1'] = table_1
    response_dict['table_2'] = table_2

    return json.dumps(response_dict)


def run_model_job(p_config, p_ver, p_type):
    """

    """
    success = False
    msg = 'connect_db_failed'
    data = None
    timestamp = None
    # NOTE step-1 connection ?????????
    db_conn_mpp = create_connection()
    # if True:
    if db_conn_mpp is not None:
        sheet7_B4, sheet7_C4, sheet7_D4, sheet7_B5, sheet7_C5, sheet7_B6, sheet7_C6, sheet7_B7, sheet7_C7, sheet7_D7, sheet7_B8, sheet7_C8, sheet7_D8, sheet7_B9, sheet7_C9, sheet7_B13, sheet7_C13, sheet7_D13, sheet7_B14, sheet7_C14, sheet7_D14, type2_best_B6, type2_best_C6, type3_best_B4_ADD, type3_best_C4_ADD, type4_best_B4_ADD, type4_best_C4_ADD, type4_best_total_ADD \
            = MODELJob(p_config=p_config,
                       p_db_conn_mpp=db_conn_mpp, p_ver=p_ver, p_type=p_type).execute()
        data = {'B4': sheet7_B4, 'C4': sheet7_C4, 'D4': sheet7_D4, 'B5': sheet7_B5, 'C5': sheet7_C5, 'B6': sheet7_B6,
                'C6': sheet7_C6, 'B7': sheet7_B7, 'C7': sheet7_C7, 'D7': sheet7_D7, 'B8': sheet7_B8,
                'C8': sheet7_C8, 'D8': sheet7_D8, 'B9': sheet7_B9, 'C9': sheet7_C9, 'B13': sheet7_B13,
                'C13': sheet7_C13,
                'D13': sheet7_D13, 'B14': sheet7_B14, 'C14': sheet7_C14,
                'D14': sheet7_D14, 'type2_best_B6': type2_best_B6, 'type2_best_C6': type2_best_C6,
                'type3_best_B4_ADD': type3_best_B4_ADD, 'type3_best_C4_ADD': type3_best_C4_ADD,
                'type4_best_B4_ADD': type4_best_B4_ADD, 'type4_best_C4_ADD': type4_best_C4_ADD,
                'type4_best_total_ADD': type4_best_total_ADD}
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        # print(data)
        # print(timestamp)
        success = True
        msg = 'ok'
    else:
        pass

    try:
        util.closeConnection(db_conn_mpp)
        # util.closeConnection(db_conn_rds)
        # util.closeConnection(db_conn_dbprod7)
    except Exception as e:
        traceback.print_exc()

    # NOTE table-1
    table_1 = list()
    table_1.append({'desc': '本月计划铁水量，万吨/月',
                    'yi': sheet7_B4,
                    'er': sheet7_C4,
                    'heji': sheet7_D4})
    table_1.append({'desc': '标准铁水比',
                    'yi': sheet7_B5,
                    'er': sheet7_C5,
                    'heji': '--'})
    table_1.append({'desc': '拟铁水比',
                    'yi': sheet7_B6,
                    'er': sheet7_C6,
                    'heji': '--'})
    table_1.append({'desc': '本月计划钢产量，万吨',
                    'yi': sheet7_B7,
                    'er': sheet7_C7,
                    'heji': sheet7_D7})
    table_1.append({'desc': '本月计划钢水产量，万吨',
                    'yi': sheet7_B8,
                    'er': sheet7_C8,
                    'heji': sheet7_D8})
    table_1.append({'desc': '连铸收得率',
                    'yi': sheet7_B9,
                    'er': sheet7_C9,
                    'heji': '--'})
    # 如果type = 2时，额外加一行，一炼钢最优的铁水比：type2_best_B6，二炼钢最优铁水比：type2_best_C6
    if p_type == 2:
        table_1.append({'desc': '最优铁水比',
                        'yi': type2_best_B6,
                        'er': type2_best_C6,
                        'heji': '--'})
    # 如果type = 3时，额外加一行，当增加一吨铁水时，一炼钢最优的增加的铁水量：type3_best_B4_ADD，二炼钢最优的增加的铁水量：type3_best_C4_ADD
    if p_type == 3:
        table_1.append({'desc': '当增加一吨铁水时，最优增加的铁水量',
                        'yi': type3_best_B4_ADD,
                        'er': type3_best_C4_ADD,
                        'heji': (type3_best_B4_ADD + type3_best_C4_ADD)})
    # 如果type = 4时，额外加一行，在铁水比范围内，增加type4_best_total_ADD吨铁水最优，其中一炼钢最优的增加的铁水量：type4_best_B4_ADD，
    # 二炼钢最优的增加的铁水量：type4_best_C4_ADD
    if p_type == 4:
        table_1.append({'desc': f'在铁水比范围内，增加{type4_best_total_ADD}吨铁水最优',
                        'yi': type4_best_B4_ADD,
                        'er': type4_best_C4_ADD,
                        'heji': (type4_best_B4_ADD + type4_best_C4_ADD)})

    # NOTE table-2
    table_2 = list()
    table_2.append({'desc': '炼钢成本变化值，万元',
                    'yi': sheet7_B13,
                    'er': sheet7_C13,
                    'heji': sheet7_D13})
    table_2.append({'desc': '炼钢吨钢成本变化值，元/吨',
                    'yi': sheet7_B14,
                    'er': sheet7_C14,
                    'heji': sheet7_D14})

    return success, msg, data, timestamp, table_1, table_2


def create_connection():
    try:
        db_conn_mpp = util.getConnectionDb2(config.DB_HOST_MPP_DB2,
                                            config.DB_PORT_MPP_DB2,
                                            config.DB_DBNAME_MPP_DB2,
                                            config.DB_USER_MPP_DB2,
                                            config.DB_PASSWORD_MPP_DB2)
        # print('connect db_conn_mpp success')
        #
        # db_conn_dbprod7 = util.getConnectionDb2(config.DB_HOST_DBPROD7_DB2,
        #                                         config.DB_PORT_DBPROD7_DB2,
        #                                         config.DB_DBNAME_DBPROD7_DB2,
        #                                         config.DB_USER_DBPROD7_DB2,
        #                                         config.DB_PASSWORD_DBPROD7_DB2)
        # print('connect db_conn_dbprod7 success')
        # db_conn_rds = util.getConnectionDb2(config.DB_HOST_RDS_DB2,
        #                                     config.DB_PORT_RDS_DB2,
        #                                     config.DB_DBNAME_RDS_DB2,
        #                                     config.DB_USER_RDS_DB2,
        #                                     config.DB_PASSWORD_RDS_DB2)
        # print('connect db_conn_rds success')
    except Exception as e:
        db_conn_mpp = None
        # db_conn_rds = None
        # db_conn_dbprod7 = None
        traceback.print_exc()
    # return db_conn_mpp, db_conn_rds, db_conn_dbprod7
    return db_conn_mpp


if __name__ == '__main__':
    # exeutors = {
    #     "default": ProcessPoolExecutor(max_workers=10)
    # }
    # app.scheduler = BackgroundScheduler(exeutors=exeutors)
    # app.scheduler.add_job(run_model_job, 'interval', seconds=3,
    #                       args=[config, '20211020000000VER', 1], id='zgh')
    # app.scheduler.start()

    # NOTE
    app.run(debug=config.DEBUG, host='0.0.0.0', port=8888)
